package tree;

/**
 * Created with IntelliJ IDEA.
 * Description: 669. 修剪二叉搜索树
 * User: Li_yizYa
 * Date: 2025/6/11
 * Time: 20:43
 */
public class Solution35 {
    /**
     * 非递归
     * @param root
     * @param low
     * @param high
     * @return
     */
    public TreeNode trimBST1(TreeNode root, int low, int high) {
        if (root == null) {
            return root;
        }
        while (root != null && (root.val < low || root.val > high)) {
            if (root.val > high) {
                root = root.left;
            } else {
                root = root.right;
            }
        }
        TreeNode cur = root;
        while (cur != null) {
            while (cur.left != null && cur.left.val < low) {
                cur.left = cur.left.right;
            }
            cur = cur.left;
        }
        cur = root;
        while (cur != null) {
            while (cur.right != null && cur.right.val > high) {
                cur.right = cur.right.left;
            }
            cur = cur.right;
        }
        return root;
    }
    /**
     * 递归
     * @param root
     * @param low
     * @param high
     * @return
     */
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) {
            return root;
        }
        if (root.val > high) {
            return trimBST(root.left, low, high);
        }
        if (root.val < low) {
            return trimBST(root.right, low, high);
        }

        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);

        return root;
    }
}
